package com.yt.sys.server.api.cms;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yt.common.constant.Result;
import com.yt.sys.models.dto.SysPermissionDTO;
import com.yt.sys.models.entity.SysPermission;
import com.yt.sys.models.service.ISysPermissionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/cms/sys/permission")
@Api(tags = "系统管理-权限管理")
public class SysPermissionController {

    @Autowired
    private ISysPermissionService sysPermissionService;

    @GetMapping("/list")
    @ApiOperation("权限列表")
    public Result<List<SysPermission>> list() {
        QueryWrapper<SysPermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", 0);
        queryWrapper.orderByDesc("create_time");
        List<SysPermission> list = sysPermissionService.list(queryWrapper);
        return Result.success(list);
    }

    @GetMapping("/page")
    @ApiOperation("权限分页列表")
    public Result<Page<SysPermission>> page(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String permName,
            @RequestParam(required = false) String permUrl,
            @RequestParam(required = false) String module) {
        Page<SysPermission> page = new Page<>(pageNum, pageSize);
        QueryWrapper<SysPermission> queryWrapper = new QueryWrapper<>();
        
        // 添加搜索条件
        if (permName != null && !permName.isEmpty()) {
            queryWrapper.like("perm_name", permName);
        }
        if (permUrl != null && !permUrl.isEmpty()) {
            queryWrapper.like("perm_url", permUrl);
        }
        if (module != null && !module.isEmpty()) {
            queryWrapper.like("module", module);
        }
        
        queryWrapper.orderByDesc("create_time");
        Page<SysPermission> result = sysPermissionService.page(page, queryWrapper);
        return Result.success(result);
    }

    @GetMapping("/{id}")
    @ApiOperation("根据ID获取权限信息")
    public Result<SysPermission> getById(@PathVariable Integer id) {
        SysPermission permission = sysPermissionService.getById(id);
        if (permission == null || permission.getIsDelete() == 1) {
            return Result.fail("权限不存在");
        }
        return Result.success(permission);
    }

    @PostMapping
    @ApiOperation("新增权限")
    public Result<String> add(@Valid @RequestBody SysPermissionDTO sysPermissionDTO) {
        // 检查权限名称是否已存在
        QueryWrapper<SysPermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("perm_name", sysPermissionDTO.getPermName());
        queryWrapper.eq("is_delete", 0);
        if (sysPermissionService.count(queryWrapper) > 0) {
            return Result.fail("权限名称已存在");
        }

        // 检查权限路径是否已存在
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("perm_url", sysPermissionDTO.getPermUrl());
        queryWrapper.eq("is_delete", 0);
        if (sysPermissionService.count(queryWrapper) > 0) {
            return Result.fail("权限路径已存在");
        }

        SysPermission permission = new SysPermission();
        BeanUtils.copyProperties(sysPermissionDTO, permission);
        permission.setIsDelete(0);
        boolean result = sysPermissionService.save(permission);
        if (result) {
            return Result.success("新增成功");
        } else {
            return Result.fail("新增失败");
        }
    }

    @PutMapping
    @ApiOperation("修改权限")
    public Result<String> update(@Valid @RequestBody SysPermissionDTO sysPermissionDTO) {
        if (sysPermissionDTO.getPermId() == null) {
            return Result.fail("权限ID不能为空");
        }

        SysPermission permission = sysPermissionService.getById(sysPermissionDTO.getPermId());
        if (permission == null || permission.getIsDelete() == 1) {
            return Result.fail("权限不存在");
        }

        // 检查权限名称是否被其他人使用
        QueryWrapper<SysPermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("perm_name", sysPermissionDTO.getPermName());
        queryWrapper.eq("is_delete", 0);
        queryWrapper.ne("perm_id", sysPermissionDTO.getPermId());
        if (sysPermissionService.count(queryWrapper) > 0) {
            return Result.fail("权限名称已存在");
        }

        // 检查权限路径是否被其他人使用
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("perm_url", sysPermissionDTO.getPermUrl());
        queryWrapper.eq("is_delete", 0);
        queryWrapper.ne("perm_id", sysPermissionDTO.getPermId());
        if (sysPermissionService.count(queryWrapper) > 0) {
            return Result.fail("权限路径已存在");
        }

        BeanUtils.copyProperties(sysPermissionDTO, permission);
        boolean result = sysPermissionService.updateById(permission);
        if (result) {
            return Result.success("修改成功");
        } else {
            return Result.fail("修改失败");
        }
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除权限")
    public Result<String> delete(@PathVariable Integer id) {
        SysPermission permission = sysPermissionService.getById(id);
        if (permission == null || permission.getIsDelete() == 1) {
            return Result.fail("权限不存在");
        }

        // 使用 MyBatis-Plus 的逻辑删除功能
        boolean result = sysPermissionService.removeById(id);
        if (result) {
            return Result.success("删除成功");
        } else {
            return Result.fail("删除失败");
        }
    }
}